﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using MeTalker.Aide.Forms;
using MeTalker.Aide.DBUtility;
using MeTalker.Aide.Model;
using MeTalker.Aide.Mode;
using MeTalker.Securitys.Cryptography;

namespace MeTalker.Aide.data
{
    internal static class DataFactory
    {
        static AESHelper aes = new AESHelper();
        internal readonly static string DTAT_FILE_NAME = FileFactory.DataDirectory + "data.txt";
        internal readonly static string CUSTOMER_FILE_NAME = FileFactory.DataDirectory + "customer.cur";
        internal readonly static string IMG_PATH = "emotions/";
        internal readonly static string KEY_DTAT_AUTO = "autoback";
        internal readonly static string LIST_FILE = FileFactory.DataDirectory + "list.list";
        internal readonly static string CONFIG_FILE_NAME = FileFactory.DataDirectory + "config.xml";
        internal readonly static string MESSAGE_FILE = FileFactory.DataDirectory + "messages.xml";
        internal readonly static string ANSWER_FILE_NAME = FileFactory.DataDirectory + "answer.xml";
        internal readonly static string MENU_FILE = FileFactory.DataDirectory + "menu.xml";
        internal readonly static string TRADE_FILE = FileFactory.DataDirectory + "trades.xml";
        internal readonly static string APP_KEY_FILE = FileFactory.BaseDirectory + "appkey.dat";
        
        //internal static IDictionary<string, NodeRoot> Messages { get; private set; }
        internal static DataList DataList { get; set; }
        internal static ChatRecords ChatRecords { get; set; }
        internal static NodeList NodeLists { get; private set; }
        internal static List<ImageSource> ImageSources { get; private set; }
        internal static Config SystemConfig { get; private set; }
        internal static MessageNode Messages { get; set; }
        internal static MessageNode Answers { get; set; }
        internal static List<AnswerMod> DbAnswers { get; private set; }
        internal static ChatRecords AnswerProblem { get; private set; }
        internal static MenuNavigation Menus { get; private set; }

        internal static List<Account> Accounts { get; private set; }
        internal static TradeFullinfos Trades { get; private set; }

        //internal static TipConfig Tips { get;private set; }
        internal static User User { get; private set; }

        internal static void GetInitialization()
        {
            InitKey();
            InitConfig();
            InitMessage();
            InitData();
            InitChatData();
            InitDataList();
            InitConfig();
            InitAnswer();
            InitMenu();
            InitTrade();
        }

        static DataFactory()
        {
            Accounts = new List<Account>();
            SystemConfig = new Config();
            DbAnswers = AccessHelper.GetProblemsReader();
        }

        static void InitKey()
        {
            try
            {
                FileStream fileStream = new FileStream(APP_KEY_FILE, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] b = new byte[fileStream.Length];
                fileStream.Read(b, 0, b.Length);
                string xml = Encoding.UTF8.GetString(aes.Decrypt(b));
                using (StringReader reader = new StringReader(xml))
                {
                    XDocument doc = XDocument.Load(reader);
                    var ds = from temp in doc.Descendants("item")
                             select new Account()
                             {
                                 TopSession = temp.Element("TopSession") != null ? temp.Element("TopSession").Value : "",
                                 TopCodeReturn = temp.Element("TopCodeReturn") != null ? temp.Element("TopCodeReturn").Value : "",
                                 AccountId = temp.Element("AccountId") != null ? temp.Element("AccountId").Value : "",
                                 AppKey = temp.Element("AppKey") != null ? temp.Element("AppKey").Value : "",
                                 AppSecret = temp.Element("AppSecret") != null ? temp.Element("AppSecret").Value : "",
                                 Default = temp.Element("Default") != null ? bool.Parse(temp.Element("Default").Value) : false,
                             };
                    Accounts = ds.ToList<Account>();
                }
            }
            catch
            {
            }
        }

        static void InitTip() {

            try
            {
                XDocument doc = XDocument.Load("tip.jl");
                var ds = from temp in doc.Descendants()
                         select new TipConfig()
                         {
                             tip_double_run_str = temp.Element("tip_double_run_str") != null ? temp.Element("tip_double_run_str").Value : "",
                             tip_user_not_null_str = temp.Element("tip_user_not_null_str") != null ? temp.Element("tip_user_not_null_str").Value : "",
                             tip_password_not_null_str = temp.Element("tip_password_not_null_str") != null ? temp.Element("tip_password_not_null_str").Value : "",
                             tip_login_fail_str = temp.Element("tip_login_fail_str") != null ? temp.Element("tip_login_fail_str").Value : "",
                             tip_system_fail_str = temp.Element("tip_system_fail_str") != null ? temp.Element("tip_system_fail_str").Value : "",
                             tip_user_not_exist_str = temp.Element("tip_user_not_exist_str") != null ? temp.Element("tip_user_not_exist_str").Value : "",
                             tip_user_other_str = temp.Element("tip_user_other_str") != null ? temp.Element("tip_user_other_str").Value : "",


                             tip_user_over_vaild_str = temp.Element("tip_user_over_vaild_str") != null ? temp.Element("tip_user_over_vaild_str").Value : "",
                             tip_user_exist_str = temp.Element("tip_user_exist_str") != null ? temp.Element("tip_user_exist_str").Value : "",
                             tip_password_error_str = temp.Element("tip_password_error_str") != null ? temp.Element("tip_password_error_str").Value : "",
                             tip_conntect_error_str = temp.Element("tip_conntect_error_str") != null ? temp.Element("tip_conntect_error_str").Value : "",
                             tip_user_vaild_str = temp.Element("tip_user_vaild_str") != null ? temp.Element("tip_user_vaild_str").Value : "",
                             tip_pass_consistent_str = temp.Element("tip_pass_consistent_str") != null ? temp.Element("tip_pass_consistent_str").Value : "",

                             tip_login_fail_exit_str = temp.Element("tip_login_fail_exit_str") != null ? temp.Element("tip_login_fail_exit_str").Value : "",
                             tip_reg_success_str = temp.Element("tip_reg_success_str") != null ? temp.Element("tip_reg_success_str").Value : "",
                             tip_reg_exist_st = temp.Element("tip_reg_exist_st") != null ? temp.Element("tip_reg_exist_st").Value : "",
                             tip_reg_fail_st = temp.Element("tip_reg_fail_st") != null ? temp.Element("tip_reg_fail_st").Value : "",
                             tip_reg_already_fail_st = temp.Element("tip_reg_already_fail_st") != null ? temp.Element("tip_reg_already_fail_st").Value : "",

                         };
                //Tips = ds.FirstOrDefault();
            }
            catch
            {
            }
        }

        internal static bool InitUser(string xml)
        {
            try
            {
                using (StringReader reader = new StringReader(xml))
                {
                    XDocument doc = XDocument.Load(reader);
                    var ds = from temp in doc.Descendants()
                             select new User()
                             {
                                 Passwd = temp.Element("Passwd") != null ? temp.Element("Passwd").Value : "",
                                 UserName = temp.Element("UserName") != null ? temp.Element("UserName").Value : "",
                                 IsSuccess = temp.Element("Success") != null ? bool.Parse(temp.Element("Success").Value) : false,
                                 ExpireDate = temp.Element("EDate") != null ? temp.Element("EDate").Value : "",
                                 RegistDate = temp.Element("SDate") != null ? temp.Element("SDate").Value : "",
                                 AddDate = temp.Element("ADate") != null ? temp.Element("ADate").Value : "",
                                 SessionId = temp.Element("SId") != null ? temp.Element("SId").Value : "",
                                 Day = temp.Element("TDays") != null ? int.Parse(temp.Element("TDays").Value) : 0,
                                 UserType = temp.Element("UType") != null ? temp.Element("UType").Value : "",
                                 StartDate = temp.Element("SDate") != null ? temp.Element("SDate").Value : "",
                             };
                    User = ds.FirstOrDefault();
                    if (User == null)
                        return false;
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        static void InitInages()
        {


        }

        static void InitTrade()
        {
            Trades = SerializerFactory.DeserializeFile<TradeFullinfos>(TRADE_FILE) as TradeFullinfos;
            if (Trades == null)
                Trades = new TradeFullinfos();
        }

        static void InitMenu()
        {
            Menus = SerializerFactory.DeserializeMenu();
            if (Menus != null && Menus.Nodes != null && Menus.Nodes.Count == 1)
            {
                Menus.DefaultId = Menus.Nodes[0].Id;
            }
        }

        static void InitAnswer()
        {
            try
            {
                AnswerProblem = new data.ChatRecords();
                XDocument doc = XDocument.Load("data/Sentence.xml");
                var dd = from temp in doc.Descendants("AutoRule")
                         select new Record()
                         {
                             Cite = temp.Element("Cite") != null ? int.Parse(temp.Element("Cite").Value) : 0,
                             Time = temp.Element("Time") != null ? temp.Element("Time").Value : "",
                             Text = temp.Element("Text") != null ? temp.Element("Cite").Value : "",
                             Words = temp.Element("Words") != null ? temp.Element("Words").Value : "",
                         };
                AnswerProblem.Records = dd.ToList();

                Answers = SerializerFactory.DeserializeMessageXml(ANSWER_FILE_NAME);
            }
            catch
            {

            }
        }

        static void InitConfig()
        {
            InitImageConfig();
            try
            {
                XDocument doc = XDocument.Load(CONFIG_FILE_NAME);
                var dd = from temp in doc.Descendants("root")
                         select new Config()
                         {
                             IsHiddenLicence = temp.Element("IsHiddenLicence") != null ? bool.Parse(temp.Element("IsHiddenLicence").Value) : false,
                             IsAutoECustom = temp.Element("IsAutoECustom") != null ? bool.Parse(temp.Element("IsAutoECustom").Value) : false,
                             IsMulitOrderRemark = temp.Element("IsMulitOrderRemark") != null ? bool.Parse(temp.Element("IsMulitOrderRemark").Value) : false,
                             IsAutoAddCurrDate = temp.Element("IsAutoAddCurrDate") != null ? bool.Parse(temp.Element("IsAutoAddCurrDate").Value) : false,
                             IsAutoAddAccount = temp.Element("IsAutoAddAccount") != null ? bool.Parse(temp.Element("IsAutoAddAccount").Value) : false,
                             IsRemarkAppend = temp.Element("IsRemarkAppend") != null ? bool.Parse(temp.Element("IsRemarkAppend").Value) : false,
                             IsAutoDownloadRemark = temp.Element("IsAutoDownloadRemark") != null ? bool.Parse(temp.Element("IsAutoDownloadRemark").Value) : false,
                             IsAutoAddQueryMenu = temp.Element("IsAutoAddQueryMenu") != null ? bool.Parse(temp.Element("IsAutoAddQueryMenu").Value) : false,
                             IsSeriesThreeError = temp.Element("IsSeriesThreeError") != null ? bool.Parse(temp.Element("IsSeriesThreeError").Value) : false,
                             AutoRun = temp.Element("AutoRun") != null ?bool.Parse( temp.Element("AutoRun").Value) : false,
                             LetterTip = temp.Element("LetterTip") != null ? temp.Element("LetterTip").Value : "",
                             QueryContent = temp.Element("QueryContent") != null ? temp.Element("QueryContent").Value : "",
                             CheckSalutation = temp.Element("CheckSalutation") != null ? temp.Element("CheckSalutation").Value : "",
                             NotQuerySalutation = temp.Element("NotQuerySalutation") != null ? temp.Element("NotQuerySalutation").Value : "",
                             QuerySalutation = temp.Element("QuerySalutation") != null ? temp.Element("QuerySalutation").Value : "",
                             IsCheckProperty = temp.Element("IsCheckProperty") != null ? bool.Parse(temp.Element("IsCheckProperty").Value) : false,
                             IsCheckCustomMsg = temp.Element("IsCheckCustomMsg") != null ? bool.Parse(temp.Element("IsCheckCustomMsg").Value) : false,
                             IsBillHeader = temp.Element("IsBillHeader") != null ? bool.Parse(temp.Element("IsBillHeader").Value) : false,
                             IsCheckSendExpress = temp.Element("IsCheckSendExpress") != null ? bool.Parse(temp.Element("IsCheckSendExpress").Value) : false,
                             IsQuerySendExpress = temp.Element("IsQuerySendExpress") != null ? bool.Parse(temp.Element("IsQuerySendExpress").Value) : false,
                             IsPriorShort = temp.Element("IsPriorShort") != null ? bool.Parse(temp.Element("IsPriorShort").Value) : false,
                             IsHiddenPlatform = temp.Element("IsHiddenPlatform") != null ? bool.Parse(temp.Element("IsHiddenPlatform").Value) : false,
                             IsMenuGuideNewLine = temp.Element("IsMenuGuideNewLine") != null ? bool.Parse(temp.Element("IsMenuGuideNewLine").Value) : false,
                             IsMoveAutoClickTab = temp.Element("IsMoveAutoClickTab") != null ? bool.Parse(temp.Element("IsMoveAutoClickTab").Value) : false,
                             IsUsezBrowser = temp.Element("IsUsezBrowser") != null ? bool.Parse(temp.Element("IsUsezBrowser").Value) : false,
                             IsAutoReply = temp.Element("IsAutoReply") != null ? bool.Parse(temp.Element("IsAutoReply").Value) : false,
                             DefaultGuideMenu = temp.Element("DefaultGuideMenu") != null ? int.Parse(temp.Element("DefaultGuideMenu").Value) : 0,
                             Line = temp.Element("Line") != null ? int.Parse(temp.Element("Line").Value) : 0,
                             SelfLearn = temp.Element("SelfLearn") != null ? bool.Parse(temp.Element("SelfLearn").Value) : false,
                         };

                SystemConfig = dd.FirstOrDefault();

                var ds = from temp in doc.Descendants("config")
                         select new UserConfig()
                         {
                             Account = temp.Element("Account") != null ? temp.Element("Account").Value : "",
                             Alias = temp.Element("Alias") != null ? temp.Element("Alias").Value : "",
                             GuideMenu = temp.Element("GuideMenu") != null ? int.Parse(temp.Element("GuideMenu").Value) : 0,
                             WorkMode = GetState(temp.Element("WorkMode") != null ? int.Parse(temp.Element("WorkMode").Value) : 0),
                         };
                SystemConfig.UserConfigs = ds.ToList<UserConfig>();
            }
            catch
            {
            }
        }

        static TalkerState GetState(int state)
        {
            return (TalkerState)state;
        }

        static void InitImageConfig()
        {
            try
            {
                XDocument doc = XDocument.Load("emotions/EmotionConfig.xml");
                var dd = from temp in doc.Descendants("Item")
                         select new ImageSource()
                         {
                             ShortCut = temp.Element("ShortCut") != null ? temp.Element("ShortCut").Value : "",
                             Meaning = temp.Element("Meaning") != null ? temp.Element("Meaning").Value : "",
                             OriginalFile = temp.Element("OriginalFile") != null ? temp.Element("OriginalFile").Value : "",
                             FixedFile = temp.Element("FixedFile") != null ? temp.Element("FixedFile").Value : "",
                         };
                ImageSources = dd.ToList<ImageSource>();
            }
            catch
            {
            }
        }

        static void InitDataList()
        {
            NodeLists = SerializerFactory.DeserializeListXml(LIST_FILE);
        }

        static void InitChatData()
        {
            ChatRecords = SerializerFactory.DeserializeChatXml();
            if (ChatRecords == null)
                ChatRecords = new ChatRecords();
        }

        static void InitData()
        {
            DataList = SerializerFactory.DeserializeData(DTAT_FILE_NAME);
        }

        static void InitMessage()
        {
            Messages = SerializerFactory.DeserializeMessageXml(MESSAGE_FILE);

            //try
            //{
            //    foreach (var fileName in FileFactory.XmlFiles)
            //    {
            //        NodeRoot root = SerializerFactory.DeserializeXml(fileName);
            //        if (root != null)
            //        {
            //            Messages.Add(root.Title, root);
            //        }
            //    }
            //}
            //catch { }
        }
    }

    internal static class FileFactory
    {
        internal  readonly static string BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
        internal readonly static string DataDirectory = BaseDirectory + @"data\";
        internal readonly static string FILE_NAME_GOODS_LIST_ITEM = BaseDirectory + @"data\goodslist.xml";

        internal static List<string> XmlFiles { get; private set; }
        static FileFactory()
        {
            XmlFiles = new List<string>();
            string[] fileList = System.IO.Directory.GetFileSystemEntries(BaseDirectory + "data");
            foreach (string file in fileList)
            {
                if (File.Exists(file) && file.EndsWith(".xml"))
                {
                    XmlFiles.Add(file);
                }
            }
        }

        internal static bool WriterFile(string fileName, byte[] content)
        {
            try
            {
                using (FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    fileStream.Write(content, 0, content.Length);
                    fileStream.Flush();
                    fileStream.Close();
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        internal static byte[] ReaderFile(string fileName)
        {
            try
            {
                using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    byte[] b = new byte[fileStream.Length];
                    fileStream.Read(b, 0, b.Length);
                    fileStream.Flush();
                    fileStream.Close();
                    return b;
                }
            }
            catch(Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("ReaderFile", ex);
                return null;
            }
        }
    }

    internal static class SerializerFactory
    {
        internal static void ToAppKeyFile()
        {
            try
            {
                List<Account> accounts = DataFactory.Accounts;
                StringBuilder sb = new StringBuilder();
                sb.Append("<root>");
                foreach (var account in accounts)
                {
                    sb.Append("<item>");
                    //sb.Append(string.Format("<TopCodeReturn>{0}</TopCodeReturn>", account.TopCodeReturn));
                    sb.Append(string.Format("<TopSession>{0}</TopSession>", account.TopSession));
                    sb.Append(string.Format("<Default>{0}</Default>", account.Default));
                    sb.Append(string.Format("<AccountId>{0}</AccountId>", account.AccountId));
                    sb.Append(string.Format("<AppKey>{0}</AppKey>", account.AppKey));
                    sb.Append(string.Format("<AppSecret>{0}</AppSecret>", account.AppSecret));
                    sb.Append("</item>");
                }
                sb.Append("</root>");
                byte[] b = new AESHelper().Encrypt(Encoding.UTF8.GetBytes(sb.ToString()));
                using (FileStream filestream = new FileStream(DataFactory.APP_KEY_FILE, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    filestream.Write(b, 0, b.Length);
                    filestream.Flush();
                }
            }
            catch { }
        }

        internal static void SaveConfig()
        {
            try
            {
                using (FileStream fileStream = new FileStream(DataFactory.CONFIG_FILE_NAME, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("<root>");
                    sb.AppendLine(string.Format("<IsHiddenLicence>{0}</IsHiddenLicence>", DataFactory.SystemConfig.IsHiddenLicence));
                    sb.AppendLine(string.Format("<IsAutoECustom>{0}</IsAutoECustom>", DataFactory.SystemConfig.IsAutoECustom));
                    sb.AppendLine(string.Format("<IsMulitOrderRemark>{0}</IsMulitOrderRemark>", DataFactory.SystemConfig.IsMulitOrderRemark));
                    sb.AppendLine(string.Format("<IsAutoAddCurrDate>{0}</IsAutoAddCurrDate>", DataFactory.SystemConfig.IsAutoAddCurrDate));
                    sb.AppendLine(string.Format("<IsAutoAddAccount>{0}</IsAutoAddAccount>", DataFactory.SystemConfig.IsAutoAddAccount));
                    sb.AppendLine(string.Format("<IsRemarkAppend>{0}</IsRemarkAppend>", DataFactory.SystemConfig.IsRemarkAppend));
                    sb.AppendLine(string.Format("<IsAutoDownloadRemark>{0}</IsAutoDownloadRemark>", DataFactory.SystemConfig.IsAutoDownloadRemark));
                    sb.AppendLine(string.Format("<IsAutoAddQueryMenu>{0}</IsAutoAddQueryMenu>", DataFactory.SystemConfig.IsAutoAddQueryMenu));
                    sb.AppendLine(string.Format("<IsSeriesThreeError>{0}</IsSeriesThreeError>", DataFactory.SystemConfig.IsSeriesThreeError));
                    sb.AppendLine(string.Format("<AutoRun>{0}</AutoRun>", DataFactory.SystemConfig.AutoRun));
                    sb.AppendLine(string.Format("<LetterTip>{0}</LetterTip>", DataFactory.SystemConfig.LetterTip));
                    sb.AppendLine(string.Format("<QueryContent>{0}</QueryContent>", DataFactory.SystemConfig.QueryContent));
                    sb.AppendLine(string.Format("<CheckSalutation>{0}</CheckSalutation>", DataFactory.SystemConfig.CheckSalutation));
                    sb.AppendLine(string.Format("<NotQuerySalutation>{0}</NotQuerySalutation>", DataFactory.SystemConfig.NotQuerySalutation));
                    sb.AppendLine(string.Format("<QuerySalutation>{0}</QuerySalutation>", DataFactory.SystemConfig.QuerySalutation));
                    sb.AppendLine(string.Format("<IsCheckProperty>{0}</IsCheckProperty>", DataFactory.SystemConfig.IsCheckProperty));
                    sb.AppendLine(string.Format("<IsCheckCustomMsg>{0}</IsCheckCustomMsg>", DataFactory.SystemConfig.IsCheckCustomMsg));
                    sb.AppendLine(string.Format("<IsBillHeader>{0}</IsBillHeader>", DataFactory.SystemConfig.IsBillHeader));
                    sb.AppendLine(string.Format("<IsCheckSendExpress>{0}</IsCheckSendExpress>", DataFactory.SystemConfig.IsCheckSendExpress));
                    sb.AppendLine(string.Format("<IsQuerySendExpress>{0}</IsQuerySendExpress>", DataFactory.SystemConfig.IsQuerySendExpress));
                    sb.AppendLine(string.Format("<IsPriorShort>{0}</IsPriorShort>", DataFactory.SystemConfig.IsPriorShort));
                    sb.AppendLine(string.Format("<IsHiddenPlatform>{0}</IsHiddenPlatform>", DataFactory.SystemConfig.IsHiddenPlatform));
                    sb.AppendLine(string.Format("<IsMenuGuideNewLine>{0}</IsMenuGuideNewLine>", DataFactory.SystemConfig.IsMenuGuideNewLine));
                    sb.AppendLine(string.Format("<IsMoveAutoClickTab>{0}</IsMoveAutoClickTab>", DataFactory.SystemConfig.IsMoveAutoClickTab));
                    sb.AppendLine(string.Format("<IsUsezBrowser>{0}</IsUsezBrowser>", DataFactory.SystemConfig.IsUsezBrowser));
                    sb.AppendLine(string.Format("<IsAutoReply>{0}</IsAutoReply>", DataFactory.SystemConfig.IsAutoReply));
                    sb.AppendLine(string.Format("<DefaultGuideMenu>{0}</DefaultGuideMenu>", DataFactory.SystemConfig.DefaultGuideMenu));
                    sb.AppendLine(string.Format("<Line>{0}</Line>", DataFactory.SystemConfig.Line));
                    sb.AppendLine(string.Format("<SelfLearn>{0}</SelfLearn>", DataFactory.SystemConfig.SelfLearn));
                    foreach (var user in DataFactory.SystemConfig.UserConfigs)
                    {
                        sb.AppendLine("<config>");
                        sb.AppendLine(string.Format("<Account>{0}</Account>", user.Account));
                        sb.AppendLine(string.Format("<Alias>{0}</Alias>", user.Alias));
                        sb.AppendLine(string.Format("<GuideMenu>{0}</GuideMenu>", user.GuideMenu));
                        sb.AppendLine(string.Format("<WorkMode>{0}</WorkMode>", (int)user.WorkMode));
                        sb.AppendLine("</config>");
                    }
                    sb.AppendLine("</root>");
                    byte[] b = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                    fileStream.Write(b, 0, b.Length);
                    fileStream.Flush();
                    fileStream.Close();
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("SaveConfig", ex);
            }
        }
        internal static void SerializeXml(string xmlFile, Node root)
        {
            using (FileStream fileStream = new FileStream(xmlFile, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Node));
                xmlSerializer.Serialize(fileStream, root);
            }
        }
        internal static void SerializeXml(string xmlFile, NodeList root)
        {
            using (FileStream fileStream = new FileStream(DataFactory.LIST_FILE, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(NodeList));
                xmlSerializer.Serialize(fileStream, root);
            }
        }
        internal static void SerializeXml(string xmlFile, ChatRecords root)
        {
            using (FileStream fileStream = new FileStream(xmlFile, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(ChatRecords));
                xmlSerializer.Serialize(fileStream, root);
            }
        }
        internal static void SerializeXml(NodeList root)
        {
            SerializeXml(FileFactory.DataDirectory + root.FileName, root);
        }
        internal static void SerializeXml(Node root)
        {
            SerializeXml(FileFactory.DataDirectory + root.FileName, root);
        }
        internal static void SerializeXml(MenuNavigation node)
        {
            using (FileStream fileStream = new FileStream(DataFactory.MENU_FILE, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(MenuNavigation));
                xmlSerializer.Serialize(fileStream, node);
            }
        }
        internal static void SerializeXml(MessageNode node)
        {
            using (FileStream fileStream = new FileStream(DataFactory.MESSAGE_FILE, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(MessageNode));
                xmlSerializer.Serialize(fileStream, node);
            }
        }
        internal static void SerializeXml(string xmlFile, MessageNode node)
        {
            using (FileStream fileStream = new FileStream(xmlFile, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(MessageNode));
                xmlSerializer.Serialize(fileStream, node);
            }
        }
        internal static void SerializeXml(string xmlFile, DataList root)
        {
            using (FileStream fileStream = new FileStream(xmlFile, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataList));
                xmlSerializer.Serialize(fileStream, root);
            }
        }
        internal static void SerializeData(DataList root)
        {
            using (FileStream fileStream = new FileStream(DataFactory.DTAT_FILE_NAME, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataList));
                xmlSerializer.Serialize(fileStream, root);
            }
        }
        #region 泛型
        internal static void SerializeFile<T>(T root, string fileName)
        {
            try
            {
                using (FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    xmlSerializer.Serialize(fileStream, root);
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("Serialize", ex);
            }
        }

        internal static object DeserializeFile<T>(string fileName)
        {
            try
            {
                using (FileStream memoryStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    return xmlSerializer.Deserialize(memoryStream);
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("Deserialize", ex);
                return null;
            }
        }

        internal static void Serialize<T>(T root, string xml)
        {
            try
            {
                using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    xmlSerializer.Serialize(memoryStream, root);
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("Serialize", ex);
            }
        }

        internal static object Deserialize<T>(string xml)
        {
            try
            {
                using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    return xmlSerializer.Deserialize(memoryStream);
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("Deserialize", ex);
                return null;
            }
        }
        #endregion
        internal static Node DeserializeXml(string xmlFile)
        {
            try
            {
                using (FileStream fileStream = new FileStream(xmlFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Node));
                    return xmlSerializer.Deserialize(fileStream) as Node;
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("SaveConfig", ex);
            }
            return null;
        }
        internal static ChatRecords DeserializeChatXml()
        {
            try
            {
                using (FileStream fileStream = new FileStream(DataFactory.CUSTOMER_FILE_NAME, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(ChatRecords));
                    return xmlSerializer.Deserialize(fileStream) as ChatRecords;
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("SaveConfig", ex);
                return null;
            }
        }
        internal static NodeList DeserializeListXml(string xmlFile)
        {
            try
            {
                using (FileStream fileStream = new FileStream(xmlFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(NodeList));
                    return xmlSerializer.Deserialize(fileStream) as NodeList;
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("SaveConfig", ex);
                return null;
            }
        }
        internal static MessageNode DeserializeMessageXml(string xmlFile)
        {
            try
            {
                using (FileStream fileStream = new FileStream(xmlFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(MessageNode));
                    return xmlSerializer.Deserialize(fileStream) as MessageNode;
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("SaveConfig", ex);
                return null;
            }
        }
        internal static MenuNavigation DeserializeMenu()
        {
            try
            {
                using (FileStream fileStream = new FileStream(DataFactory.MENU_FILE, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(MenuNavigation));
                    return xmlSerializer.Deserialize(fileStream) as MenuNavigation;
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("DeserializeMenu", ex);
                return null;
            }
        }
        internal static DataList DeserializeData(string dataFile)
        {
            try
            {
                using (FileStream fileStream = new FileStream(dataFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataList));
                    return xmlSerializer.Deserialize(fileStream) as DataList;
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("SaveConfig", ex);
                return null;
            }
        }
    }

    internal static class NodeFactory
    {
        static void ToChildNode(List<Node> nodes, TreeNode noderoot)
        {
            foreach (var nodestr in nodes)
            {
                TreeNode temp1 = new TreeNode();
                temp1.Text = nodestr.Text;
                temp1.Tag = nodestr;
                temp1.ToolTipText = nodestr.Text;
                noderoot.Nodes.Add(temp1);
                if (nodestr.SubNode.Count > 0)
                {
                    temp1.Text = nodestr.Text;
                    ToChildNode(nodestr.SubNode, temp1);
                }
            }
        }

        internal static void ToTreeView(List<Node> nodes, TreeView treeview)
        {
            foreach (Node root in nodes)
            {
                TreeNode rootNode = new TreeNode(root.Text);
                rootNode.Tag = root;
                foreach (var d in root.SubNode)
                {
                    TreeNode childNode = new TreeNode(root.Text);
                    childNode.Tag = d;
                    childNode.Text = d.Text;
                    rootNode.Nodes.Add(childNode);
                    if (d.SubNode.Count > 0)
                        ToChildNode(d.SubNode, childNode);

                }
                treeview.Nodes.Add(rootNode);
            }
        }

        internal static void SetListNode(Node root, TreeView treeView)
        {
            try
            {
                if (treeView == null)
                {
                    return;
                }
                treeView.Nodes.Clear();

                foreach (var nodestr in root.SubNode)
                {
                    TreeNode temp1 = new TreeNode();
                    temp1.ToolTipText = nodestr.Text;
                    temp1.Text = nodestr.Text;
                    temp1.Tag = nodestr;
                    //noderoot.Nodes.Add(temp1);
                    if (nodestr.SubNode.Count > 0)
                    {
                        //temp1.Text = nodestr.Text;
                        ToChildNode(nodestr.SubNode, temp1);
                    }
                    treeView.Nodes.Add(temp1);//把treeRoot节点放到treeview控件里
                }

                //foreach (var nodestr in root.Nodes)
                //{
                //TreeNode treeRoot = new TreeNode();
                //treeRoot.Text = root.Text;
                //treeRoot.Tag = root;
                //TreeNode node = new TreeNode();
                //node.Text = node.Text;
                //ToChildNode(root.SubNode, node);
                //treeView.Nodes.Add(node);//把treeRoot节点放到treeview控件里
                //foreach (Node rootNode in root.SubNode)
                //{
                //    TreeNode node = new TreeNode();
                //    node.Text = rootNode.Text;
                //    if (root.SubNode.Count > 0)
                //    {
                //        AddNode(root.SubNode, node);
                //    }
                //    treeView.Nodes.Add(node);//把treeRoot节点放到treeview控件里
                //}

                //}
            }
            catch { }
        }

        static void AddNode(List<Node> nodes, TreeNode noderoot)
        {
            foreach (var nodestr in nodes)
            {
                TreeNode temp1 = new TreeNode();
                temp1.ToolTipText = nodestr.Text;
                temp1.Text = nodestr.Text;
                temp1.Tag = nodestr;
                noderoot.Nodes.Add(temp1);
                if (nodestr.SubNode.Count > 0)
                {
                    temp1.Text = nodestr.Text;
                    AddNode(nodestr.SubNode, temp1);
                }

            }
        }

        internal static void SetNode(Node root, TreeView treeView)
        {
            try
            {
                if (treeView == null)
                {
                    return;
                }
                treeView.Nodes.Clear();

                foreach (var nodestr in root.SubNode)
                {
                    TreeNode treeRoot = new TreeNode();
                    treeRoot.Text = nodestr.Text;
                    treeRoot.Tag = nodestr;
                    treeRoot.ToolTipText = nodestr.Text;
                    if (nodestr.SubNode.Count > 0)
                    {
                        //treeRoot.Text = nodestr.Key;
                        AddNode(nodestr.SubNode, treeRoot);
                    }
                    treeView.Nodes.Add(treeRoot);//把treeRoot节点放到treeview控件里
                }
            }
            catch { }
        }

        internal static void SetNode(List<Node> root, TreeView treeView)
        {
            try
            {
                if (treeView == null)
                {
                    return;
                }
                treeView.Nodes.Clear();

                foreach (var nodestr in root)
                {
                    TreeNode treeRoot = new TreeNode();
                    treeRoot.ToolTipText = nodestr.Text;
                    treeRoot.Text = nodestr.Text;
                    treeRoot.Tag = nodestr;
                    if (nodestr.SubNode.Count > 0)
                    {
                        //treeRoot.Text = nodestr.Key;
                        AddNode(nodestr.SubNode, treeRoot);
                    }
                    treeView.Nodes.Add(treeRoot);//把treeRoot节点放到treeview控件里
                }
            }
            catch { }
        }

        internal static void SetAllDataToTreeView(TreeView treeView)
        {
            try
            {
                if (treeView == null)
                {
                    return;
                }
                treeView.Nodes.Clear();
                foreach (var nodes in DataFactory.Messages.Nodes)
                {
                    TreeNode root = new TreeNode();
                    root.Text = nodes.Text;
                    root.ToolTipText = nodes.Text;
                    foreach (var nodestr in nodes.SubNode)
                    {
                        TreeNode treeRoot = new TreeNode();
                        treeRoot.ToolTipText = nodestr.Text;
                        treeRoot.Text = nodestr.Text;
                        treeRoot.Tag = nodestr;
                        if (nodestr.SubNode.Count > 0)
                        {
                            treeRoot.Text = nodestr.Key;
                            AddNode(nodestr.SubNode, treeRoot);
                        }
                        root.Nodes.Add(treeRoot);

                    }
                    treeView.Nodes.Add(root);//把treeRoot节点放到treeview控件里
                }
            }
            catch { }
        }
    }

    public enum DataType
    {
        Log = 1,
        Remarks = 2,
        Reply = 3,
        Receive = 4,
        Send = 5
    }

    public class Data
    {
        [XmlElement(ElementName = "Keyword")]
        public string Keyword { get; set; }
        [XmlElement(ElementName = "Text")]
        public string Text { get; set; }
        [XmlElement(ElementName = "Time")]
        public string Time { get; set; }
        [XmlAttribute(AttributeName = "Key")]
        public string Key { get; set; }
        [XmlAttribute(AttributeName = "Type")]
        public DataType DateType { get; set; }
        [XmlAttribute(AttributeName = "Recorder")]
        public string Recorder { get; set; }
        [XmlAttribute(AttributeName = "Receiver")]
        public string Receiver { get; set; }
        [XmlAttribute(AttributeName = "Alias")]
        public string Alias { get; set; }
    }


    public class NodeList
    {
        public NodeList()
        {
            Nodes = new List<Node>();
        }
        [XmlAttribute(AttributeName = "title")]
        public string Title { get; set; }

        [XmlAttribute(AttributeName = "fileName")]
        public string FileName { get; set; }

        [XmlElement(ElementName = "NodeRoot")]
        public List<Node> Nodes { get; set; }
    }

    [XmlRoot(ElementName = "Root")]
    public class DataList
    {
        public DataList()
        {
            Nodes = new List<Data>();
        }
        [XmlElement(ElementName = "Node")]
        public List<Data> Nodes { get; set; }
    }

    public class ChatRecords
    {
        public ChatRecords()
        {
            Records = new List<Record>();
        }
        [XmlElement(ElementName = "Records")]
        public List<Record> Records { get; set; }
    }

    public class Record
    {
        public Record()
        {
            IsAddMessage = "加入分类短语库";
        }
        [XmlElement(ElementName = "Text")]
        public string Text { get; set; }
        [XmlElement(ElementName = "Name")]
        public string Name { get; set; }
        [XmlElement(ElementName = "Account")]
        public string Account { get; set; }
        [XmlElement(ElementName = "Words")]
        public string Words { get; set; }
        [XmlElement(ElementName = "Time")]
        public string Time { get; set; }
        [XmlAttribute(AttributeName = "DateType")]
        public DataType DateType { get; set; }
        [XmlAttribute(AttributeName = "Cite")]
        public int Cite { get; set; }
        public string IsAddMessage { get; set; }
    }

    [XmlRoot(ElementName = "Root")]
    public class MenuNavigation
    {
        public MenuNavigation()
        {
            Nodes = new List<MessageNode>();
            DefaultId = 1;
        }
        [XmlAttribute(AttributeName = "Id")]
        public int DefaultId { get; set; }

        [XmlAttribute(AttributeName = "title")]
        public string Title { get; set; }

        [XmlElement(ElementName = "Menu")]
        public List<MessageNode> Nodes { get; set; }
    }

    [XmlRoot(ElementName = "Root")]
    public class MessageNode
    {
        public MessageNode()
        {
            Nodes = new List<Node>();
        }
        [XmlAttribute(AttributeName = "title")]
        public string Title { get; set; }

        [XmlAttribute(AttributeName = "Id")]
        public int Id { get; set; }

        [XmlElement(ElementName = "Message")]
        public List<Node> Nodes { get; set; }
    }

    public class Node
    {
        public Node()
        {
            SubNode = new List<Node>();
        }
        [XmlAttribute(AttributeName = "fileName")]
        public string FileName { get; set; }
        [XmlAttribute(AttributeName = "Text")]
        public string Text { get; set; }
        [XmlAttribute(AttributeName = "Key")]
        public string Key { get; set; }
        [XmlAttribute(AttributeName = "Keyword1")]
        public string Keyword1 { get; set; }
        [XmlAttribute(AttributeName = "Keyword2")]
        public string Keyword2 { get; set; }
        [XmlAttribute(AttributeName = "Keyword3")]
        public string Keyword3 { get; set; }
        [XmlAttribute(AttributeName = "Keyword4")]
        public string Keyword4 { get; set; }
        [XmlAttribute(AttributeName = "Keyword5")]
        public string Keyword5 { get; set; }
        [XmlAttribute(AttributeName = "Keyword6")]
        public string Keyword6 { get; set; }
        [XmlAttribute(AttributeName = "Keyword7")]
        public string Keyword7 { get; set; }
        [XmlAttribute(AttributeName = "Keyword8")]
        public string Keyword8 { get; set; }
        [XmlAttribute(AttributeName = "Keyword")]
        public string Keyword { get; set; }
        [XmlElement(ElementName = "Node")]
        public List<Node> SubNode { get; set; }
    }

    internal class ImageSource
    {
        internal string ShortCut { get; set; }
        internal string Meaning { get; set; }
        internal string OriginalFile { get; set; }
        internal string FixedFile { get; set; }
    }
    internal class Config
    {
        public Config()
        {
            AutoQuerySalutation = "您好: 我是机器人(乐乐), 正在帮你查找，请稍候....";
            UserConfigs = new List<UserConfig>();
            IsAutoReply = true;
            SelfLearn = true;
            IsUsezBrowser = true;
            Line = 5;
        }
        internal string AutoQuerySalutation { get; set; }
        internal bool IsHiddenLicence { get; set; }
        internal bool IsAutoECustom { get; set; }
        internal bool IsMulitOrderRemark { get; set; }
        internal bool IsAutoAddCurrDate { get; set; }
        internal bool IsAutoAddAccount { get; set; }
        internal bool IsRemarkAppend { get; set; }
        internal bool IsAutoDownloadRemark { get; set; }
        internal bool IsAutoAddQueryMenu { get; set; }
        internal bool IsSeriesThreeError { get; set; }
        internal bool AutoRun { get; set; }
        internal string LetterTip { get; set; }
        internal string QueryContent { get; set; }
        internal string CheckSalutation { get; set; }
        internal string NotQuerySalutation { get; set; }
        internal string QuerySalutation { get; set; }
        internal bool IsCheckProperty { get; set; }
        internal bool IsCheckCustomMsg { get; set; }
        internal bool IsBillHeader { get; set; }
        internal bool IsQuerySendExpress { get; set; }
        internal bool IsCheckSendExpress { get; set; }
        internal bool IsPriorShort { get; set; }
        internal bool IsHiddenPlatform { get; set; }
        internal bool IsUsezBrowser { get; set; }
        internal int DefaultGuideMenu { get; set; }
        internal List<UserConfig> UserConfigs { get; set; }
        internal bool IsAutoReply { get; set; }
        internal int Line { get; set; }
        internal bool IsMenuGuideNewLine { get; set; }
        internal bool IsMoveAutoClickTab { get; set; }
        internal bool SelfLearn { get; set; }
    }
    public class UserConfig
    {
        internal TalkerState WorkMode { get; set; }
        public string Alias { get; set; }
        public string Account { get; set; }
        internal int GuideMenu { get; set; }

        public string MenuName
        {
            get
            {
                try
                {
                    var ds = from temp in DataFactory.Menus.Nodes where temp.Id == GuideMenu select temp;
                    MessageNode node = ds.FirstOrDefault();
                    if (node != null)
                        return node.Title;
                }
                catch
                {
                }
                return "";
            }
        }
    }

    public class TradeFullinfos {
        public TradeFullinfos() {
            TradeFulls = new List<Top.Api.Response.TradeFullinfoGetResponse>();
        }
        [XmlElement(ElementName = "Trades")]
        public List<Top.Api.Response.TradeFullinfoGetResponse> TradeFulls { get; set; }
    }

    internal class TipConfig
    {
        internal string tip_double_run_str { get; set; }
        internal string tip_user_not_null_str { get; set; }
        internal string tip_password_not_null_str { get; set; }
        internal string tip_login_fail_str { get; set; }
        internal string tip_system_fail_str { get; set; }
        internal string tip_user_not_exist_str { get; set; }
        internal string tip_user_other_str { get; set; }
        internal string tip_user_over_vaild_str { get; set; }
        internal string tip_user_exist_str { get; set; }
        internal string tip_password_error_str { get; set; }
        internal string tip_conntect_error_str { get; set; }
        internal string tip_user_vaild_str { get; set; }
        internal string tip_pass_consistent_str { get; set; }
        internal string tip_reg_success_str { get; set; }
        internal string tip_reg_exist_st { get; set; }
        internal string tip_reg_fail_st { get; set; }
        internal string tip_reg_already_fail_st { get; set; }
        internal string tip_login_fail_exit_str { get; set; }
    }
}